const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 获取所有分类
  async getAllCategories() {
    const [categories] = await db.execute(
      'SELECT * FROM product_categories ORDER BY created_at DESC'
    );
    return categories;
  },

  // 获取分类详情
  async getCategoryById(id) {
    const [categories] = await db.execute(
      'SELECT * FROM product_categories WHERE id = ?',
      [id]
    );
    
    if (categories.length === 0) {
      throw new Error('分类不存在');
    }
    
    return categories[0];
  },

  // 创建分类
  async createCategory(nameEn, nameCn, iconClass) {
    const [result] = await db.execute(
      'INSERT INTO product_categories (name_en, name_cn, icon_class) VALUES (?, ?, ?)',
      [nameEn, nameCn, iconClass]
    );
    return result.insertId;
  },

  // 更新分类
  async updateCategory(id, nameEn, nameCn, iconClass) {
    const [result] = await db.execute(
      'UPDATE product_categories SET name_en = ?, name_cn = ?, icon_class = ? WHERE id = ?',
      [nameEn, nameCn, iconClass, id]
    );
    
    if (result.affectedRows === 0) {
      throw new Error('分类不存在');
    }
    
    return true;
  },

  // 删除分类
  async deleteCategory(id) {
    // 检查是否有商品关联此分类
    const [products] = await db.execute(
      'SELECT id FROM products WHERE category_id = ? LIMIT 1',
      [id]
    );
    
    if (products.length > 0) {
      throw new Error('无法删除，有商品关联此分类');
    }
    
    const [result] = await db.execute(
      'DELETE FROM product_categories WHERE id = ?',
      [id]
    );
    
    if (result.affectedRows === 0) {
      throw new Error('分类不存在');
    }
    
    return true;
  }
};